package org.fitweb.runners;

import org.fitweb.files.DirectoryScrounger;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static org.apache.commons.io.FileUtils.*;
import static org.fitweb.files.PathFinder.*;

/**
 * See ExampleTestSuite for a cut-and-paste example of how to run all your Fit tests as a suite.
 */
@RunWith(Parameterized.class)
public abstract class ParameterisedSuiteRunner {

    String testPath;

    @Parameterized.TestRunName
    public static String testNameFor(Object firstConstructorParam) {
        String path = (String) firstConstructorParam;
        return new File(path).toURI().toString();
    }

    public static Collection<Object[]> findTestsIn(String testSourceDirectory) {
        ArrayList<Object[]> parameters;
        try {
            File inputDirectory = new File(testSourceDirectory);
            List<File> tests = new DirectoryScrounger().locateTests(inputDirectory);
            parameters = new ArrayList<Object[]>();
            for (File test : tests) {
                parameters.add(new String[]{canonical(test)});
            }
        } catch (IOException e) {
            throw new RuntimeException("Error when searching for tests to run:", e);
        }

        return parameters;
    }

    public ParameterisedSuiteRunner(String testPath) {
        this.testPath = testPath;
    }

    @Test
    public void runFitTestSuite() throws IOException {
        if (ignored(testPath)) {
            System.err.println("===> IGNORING: " + testPath);
        } else {
            new SingleTestRunner(inputDirectory(), outputDirectory(), testPath).runSingleTest();
        }
    }

    protected boolean ignored(String testPath) throws IOException {
        return readFileToString(new File(testPath)).contains("<td>Ignore Fit Test</td>");
    }

    protected abstract String inputDirectory();

    protected abstract String outputDirectory();
}
